package com.javasm.adminapi.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.adminapi.common.Parameter;
import com.javasm.adminapi.common.exception.ExceptionEnum;
import com.javasm.adminapi.common.exception.JavasmException;
import com.javasm.adminapi.login.model.LoginUser;
import com.javasm.adminapi.module.system.dao.RoleDao;
import com.javasm.adminapi.module.system.dto.PermissionQueryDTO;
import com.javasm.adminapi.module.system.entity.Role;
import com.javasm.adminapi.module.system.entity.User;
import com.javasm.adminapi.module.system.service.RolePermissionService;
import com.javasm.adminapi.module.system.service.RoleService;
import com.javasm.adminapi.module.system.service.UserService;
import com.javasm.adminapi.module.system.vo.RoleVo;
import com.javasm.adminapi.module.system.vo.SysPermissionVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色表(Role)表服务实现类
 *
 * @author makejava
 * @since 2025-10-14 21:47:38
 */
@Service("roleService")
@Log4j2
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {


    @Override
    public PageInfo<Role> pageList(RoleVo roleVo) {
        int pageSize = roleVo.getPageSize()==null?10:roleVo.getPageSize();
        int pageNum = roleVo.getPageNum()==null?1:roleVo.getPageNum();
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        Integer id = roleVo.getId();
        if(id!=null){
            queryWrapper.eq(Role::getId,id);
        }
        String nameOrCode = roleVo.getNameOrCode();
        if (nameOrCode!=null){
            queryWrapper.and(i->{
                i.like(Role::getRoleName,nameOrCode);
                i.or();
                i.like(Role::getRoleCode,nameOrCode);
            });
        }
        List<Role> list = list(queryWrapper);
        PageInfo<Role> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    @Override
    public void saveRole(Role role) {
        if(role==null){
            throw new JavasmException(ExceptionEnum.Parameter_Null);
        }
        role.setStatus(1);
        Object principal1 = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal1 instanceof String){
            throw new JavasmException(ExceptionEnum.User_Error);
        }
        LoginUser principal = (LoginUser)principal1;
        User loginUser =  principal.getUser();

        Long id = loginUser.getId();
        role.setCreateBy(id);
        save(role);
    }

    @Override
    public void updateRole(Role role) {
        //校验参数
        Parameter.check(role);
        Long id = role.getId();
        //查询数据是否存在
        Role role1 = getById(id);
        if (role1==null){
            throw new JavasmException(ExceptionEnum.User_Not_Found);
        }
        //修改数据
        role1.setRoleName(role.getRoleName());
        role1.setRoleCode(role.getRoleCode());
        if(role.getDescription()!=null){
            role1.setDescription(role.getDescription());
        }
        updateById(role1);
    }
    @Resource
    UserService userService;



    @Override
    public void deleteByIds(List<Integer> ids) {
        boolean bol = userService.countRoleIds(ids);
        if (!bol){
            throw new JavasmException(ExceptionEnum.Role_Delete_Error);
        }
        removeBatchByIds(ids);
    }

    @Resource
    RoleDao roleDao;

    @Override
    public PageInfo<SysPermissionVo> pageSys(PermissionQueryDTO page) {
        Integer pageSize = page.getPageSize();
        Integer pageNum = page.getPageNum();
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        String name = page.getName();
        if (name!=null){
            queryWrapper.like(Role::getRoleName,name);
        }
        List<Role> list = list(queryWrapper);
        List<Long> collect = list.stream().map(role -> role.getId()).collect(Collectors.toList());

        List<SysPermissionVo> roleVos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Role role = list.get(i);
            SysPermissionVo vo = new SysPermissionVo();
            vo.setId(role.getId());
            vo.setStatus(role.getStatus());
            vo.setRoleName(role.getRoleName());
            vo.setDescription(role.getDescription());
            vo.setRoleCode(role.getRoleCode());
            Long l = roleDao.listCount(role.getId());
            vo.setSum(l); // 通过索引获取对应的用户数
            roleVos.add(vo);
        }
        PageInfo<SysPermissionVo> sysPermissionVoPageInfo = new PageInfo<>(roleVos);
        return sysPermissionVoPageInfo;
    }




}
